package com.aivin.maproutelib.bean;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;

import com.aivin.maproutelib.line.GaoDeLine;
import com.aivin.maproutelib.param.MyMarkerOption;
import com.aivin.wkmaplib.R;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.aivin.maproutelib.manager.MapRouteManager;
import com.aivin.maproutelib.param.OLineOption;
import com.aivin.maproutelib.tool.WkLogTool;


public class WkGDmap {

    private AMap aMap;
    private TextureMapView mapView;
    private LocationSource.OnLocationChangedListener mOnlocationChangedLister = null;
    private final int Z_INDEX_100 = 100;
    private boolean isFirstLoc = true;
    private Context mContext;

    public WkGDmap(TextureMapView mapView, Bundle savedInstanceState, Context context) {
        this.mapView = mapView;
        this.mContext = context;
        initMapOnCreate(savedInstanceState);
    }

    private void initMapOnCreate(Bundle savedInstanceState) {
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();

        UiSettings settings = aMap.getUiSettings();
        settings.setMyLocationButtonEnabled(true);
        settings.setZoomControlsEnabled(false); // 不显示缩放按钮
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE); // 设置定位的类型为定位模式
        aMap.setMyLocationEnabled(true);

        aMap.setMapType(AMap.MAP_TYPE_NORMAL);  // 卫星地图 MAP_TYPE_SATELLITE
        aMap.setOnMarkerDragListener(onMarkerDragListener);
        aMap.setOnMapClickListener(onMapClickListener);
        aMap.setLocationSource(locationSource);

        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ico_map_feixingqi));
        myLocationStyle.strokeColor(Color.TRANSPARENT);
        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
        aMap.setMyLocationStyle(myLocationStyle);

        AMapLocationClient mLocationClient = new AMapLocationClient(mContext);
        mLocationClient.setLocationListener(mapLocationListener  );  //设置定位回调监听
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true); //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setOnceLocation(false); //设置是否只定位一次,默认为false
        mLocationOption.setWifiActiveScan(true); //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setMockEnable(false);//设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setInterval(2000); //设置定位间隔,单位毫秒,默认为2000ms
        mLocationClient.setLocationOption(mLocationOption); //给定位客户端对象设置定位参数
        mLocationClient.startLocation(); //启动定位
    }


    /**
     * 添加边界点
     */
    private void addBoundaryMarker(LatLng latLng) {
        MapRouteManager.getInstance().addBoundaryMarker(latLng, true);
        MapRouteManager.getInstance().updateSelectMakerIcon();
    }

    private AMapLocationListener mapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation.getErrorCode() != 0) {
                WkLogTool.showLog("错误码 location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                return;
            }

            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
                aMap.moveCamera(CameraUpdateFactory.zoomTo(aMap.getMaxZoomLevel()));
                //点击定位按钮 能够将地图的中心移动到定位点
                mOnlocationChangedLister.onLocationChanged(aMapLocation);

            }
        }
    };

    private LocationSource locationSource = new LocationSource() {
        @Override
        public void activate(OnLocationChangedListener onLocationChangedListener) {
            mOnlocationChangedLister = onLocationChangedListener;
        }

        @Override
        public void deactivate() {
            mOnlocationChangedLister = null;
        }
    };

    private AMap.OnMapClickListener onMapClickListener = new AMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            //WkLogTool.showLog("--> "+latLng.latitude +"  "+latLng.longitude);
            addBoundaryMarker(latLng);
        }
    };


    private AMap.OnMarkerDragListener onMarkerDragListener = new AMap.OnMarkerDragListener() {
        @Override
        public void onMarkerDragStart(Marker marker) {
            GaoDeMarker iMarker = new GaoDeMarker(marker);
            MapRouteManager.getInstance().onMarkerDragStart(iMarker);
        }

        @Override
        public void onMarkerDrag(Marker marker) {
            GaoDeMarker iMarker = new GaoDeMarker(marker);
            MapRouteManager.getInstance().onMarkerDrag(iMarker);
        }

        @Override
        public void onMarkerDragEnd(final Marker marker) {
            GaoDeMarker iMarker = new GaoDeMarker(marker);
            MapRouteManager.getInstance().onMarkerDragEnd(iMarker);
        }
    };


    public GaoDeMarker addMarker(MyMarkerOption option) {
        BitmapDescriptor bitmapDescriptor;
        if (option.hasResId()) {
            bitmapDescriptor = BitmapDescriptorFactory.fromResource(option.getResId());
        } else {
            bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(option.getBitmapIcon());
        }
        LatLng position = option.latlng ;
        MarkerOptions markerOptions = new MarkerOptions()
                .position(new LatLng(position.latitude, position.longitude))
                .icon(bitmapDescriptor)
                .zIndex(Z_INDEX_100)
                .anchor(option.getAnchorX(), option.getAnchorY())
                .draggable(option.getDraggable());
        Marker marker = aMap.addMarker(markerOptions);
        if (marker == null) {
            return null;
        }
        marker.setFlat(true);
        return new GaoDeMarker(marker);
    }


    public Marker addAmarker(Bitmap bitmap ,LatLng latLng){
        MarkerOptions markerOptions = new MarkerOptions()
                .position(latLng)
                .icon(BitmapDescriptorFactory.fromBitmap( bitmap ))
                .anchor(0.5f, 0.5f)
                .zIndex(Z_INDEX_100) ;
        return aMap.addMarker(markerOptions);
    }

    public GaoDeLine addLine(OLineOption option) {
        return addLine(option , Z_INDEX_100);
    }

    public GaoDeLine addLine(OLineOption option, int zIndex) {
        PolylineOptions polylineOptions = new PolylineOptions();
        for (LatLng latlng : option.latlngs) {
            polylineOptions.add(latlng);
        }
        polylineOptions.color(option.strokeColor).width(option.strokeWidth).zIndex(zIndex);
        Polyline polyline = aMap.addPolyline(polylineOptions);
        return new GaoDeLine(polyline);
    }


}
